package com.ssdp.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssdp.dto.Result;
import com.ssdp.dto.UserDTO;
import com.ssdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author syo 2319615164@qq.com
 * @description 登录拦截器
 * @date 2024/3/14
 * @Copyright syo
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 设置响应编码
        response.setContentType("application/json;charset=utf-8");

        // 2. 打印拦截日志
        String requestURI = request.getRequestURI();
        log.info("用户访问了需要登录页面 {}", requestURI);

        // 3. 获取ThreadLocal中的用户信息
        UserDTO user = UserHolder.getUser();

        // 4. 用户未登录
        if(user == null) {
            log.info("用户未登录！拒绝访问！");
            objectMapper.writeValue(response.getOutputStream(), Result.fail("用户未登录！"));
            return false;

        // 5. 用户登录
        } else {
            log.info("{} 用户登录成功！", user.getNickName());
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
